import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import { addTab, timeLimit } from '@/utils/utils';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Chart,
  Geom,
  Axis,
  Tooltip,
  Legend,
} from 'bizcharts';
import {
  Card,
  Table,
  Button,
  DatePicker,
  Col,
  Row,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface HumitureListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  location: { query: any };
}

interface HumitureListState {
  pageIndex: number;
  pageSize: number;
  searchValues: any;
  rowId:number;
}

@connect(({
  humitureList: { dataInfo },
  loading,
}: any) => ({
  dataInfo,
  loading: loading.effects['humitureList/fetch'],
}))
class HumitureList extends Component<HumitureListProps, HumitureListState> {
  columns = [
    { title: '时间', dataIndex: 'createTime' },
    {
      title: '温度（ ℃）',
      dataIndex: 'temperature',
      render: (text: string) => <span style={{ color: 'rgb(100, 191, 103)' }}>{text}</span>,
    },
    {
      title: '湿度（RH）',
      dataIndex: 'humidity',
      render: (text: string) => <span style={{ color: 'rgb(79, 142, 247)' }}>{text}</span>,
    },
  ];

  state: HumitureListState = {
    pageIndex: 1,
    pageSize: 20,
    searchValues: {},
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, pervState: any) {
    const { location: { query } } = nextProps;
    const { id, ...params } = query;
    return {
      searchValues: params,
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)) {
      this.fetchDataValues();
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    if (searchValues.startTime) {
      searchValues.start_end_time = [moment().startOf('day'), moment().endOf('day')];
    }

    const {
      id,
      startTime,
      endTime,
      ...values
    } = searchValues;

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(values);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  handleExport = () => this.fetchAction('export', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    const { location: { query: { id: cabinetId } } } = this.props;

    const params = {
      pageIndex: 1,
      cabinetId,
      ...searchValues,
    };

    delete params.id;
    delete params.start_end_time;

    if (params.startTime === undefined) {
      params.startTime = moment()
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      params.endTime = moment()
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
    }

    return params;
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      if (values.start_end_time) {
        if (values.start_end_time[0]) {
          values.startTime = moment(values.start_end_time[0]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          values.startTime = '';
        }
        if (values.start_end_time[1]) {
          values.endTime = moment(values.start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          values.endTime = '';
        }
      } else {
        values.startTime = '';
        values.endTime = '';
      }
      delete values.start_end_time;

      let { location: { query } } = this.props;
      query = {
        id: query.id,
        ...values,
      };

      const { searchValues: currentQuery } = this.state;
      const realQuery = _.pick(
        query,
        Object.keys(query).filter((key: string) => query[key]),
      );
      const realCurrentQuery = _.pick(
        currentQuery,
        Object.keys(currentQuery).filter((key: string) => currentQuery[key]),
      );

      if (_.isEqual(realQuery, realCurrentQuery)) {
        this.fetchDataValues();
      } else {
        const { dispatch } = this.props;
        addTab(dispatch, {
          name: '温湿度历史数据',
          url: `${pathname}?${qs.stringify(query)}`,
          isTopMenu: true,
        });
      }
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => this.setState({ pageIndex, pageSize });

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = `humitureList/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const { pageIndex, pageSize } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      loading,
    } = this.props;

    const data = dataInfo.slice(0, dataInfo.length)
      .reduce((origin: any, item: any) => {
        const obj = {
          date: item.createTime.replace(' ', '_'),
          indicators: '温度',
          value: Number(item.temperature),
        };
        origin.push(obj);
        const retriveObj = {
          date: item.createTime.replace(' ', '_'),
          indicators: '湿度',
          value: Number(item.humidity),
        };
        origin.push(retriveObj);
        return origin;
      }, []).reverse();

    const cols = {
      date: {
        range: [0, 1],
      },
    };

    const pagination: any = dataInfo.length
      ? {
        total: dataInfo.length,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.length || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : false;

    const dataSource = dataInfo.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Form.Item label="起止时间" colon={false}>
                  {getFieldDecorator('start_end_time', {
                    initialValue: [moment().startOf('day'), moment().endOf('day')],
                  })(
                    <RangePicker
                      showTime
                      placeholder={['开始时间', '截止时间']}
                      format="YYYY/MM/DD HH:mm:ss"
                      disabledDate={timeLimit}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                          moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                        ],
                      }}
                      style={{ width: '100%' }}
                    />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card title="温湿度折线图" className="tableList" bordered={false}>
          <Chart height={400} data={data} scale={cols} forceFit>
            <Legend />
            <Axis
              name="value"
              label={{
                formatter: val => val,
              }}
            />
            <Axis
              name="date"
              label={{
                formatter: () => '',
              }}
            />
            <Tooltip
              hideMarkers
              crosshairs={{
                type: 'y',
              }}
            />
            <Geom type="line" position="date*value" size={2} color="indicators" shape="smooth" />
            <Geom
              type="point"
              position="date*value"
              size={4}
              shape="circle"
              color="indicators"
              style={{
                stroke: '#fff',
                lineWidth: 1,
              }}
            />
          </Chart>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleExport}
            >
              导出
            </Button>
          </div>

          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<HumitureListProps>()(HumitureList);
